// Auto-DSL 测试页面 JavaScript

// 页面加载完成后初始化
document.addEventListener('DOMContentLoaded', function() {
    initializePage();
    setupEventListeners();
});

// 初始化页面
async function initializePage() {
    await checkSystemHealth();
    await loadAvailableModels();
    await loadSupportedTypes();
}

// 设置事件监听器
function setupEventListeners() {
    // DSL生成表单
    document.getElementById('dslForm').addEventListener('submit', handleDslGeneration);
    
    // 业务规则表单
    document.getElementById('businessRuleForm').addEventListener('submit', handleBusinessRuleGeneration);

    // Excel上传表单
    document.getElementById('excelUploadForm').addEventListener('submit', handleExcelUpload);

    // Excel文件选择
    document.getElementById('excelFile').addEventListener('change', handleExcelFileChange);
}

// 检查系统健康状态
async function checkSystemHealth() {
    try {
        const response = await fetch('/api/dsl/health');
        const data = await response.json();
        
        const statusElement = document.getElementById('systemStatus');
        if (data.status === 'UP') {
            statusElement.className = 'badge bg-success';
            statusElement.textContent = '正常';
        } else {
            statusElement.className = 'badge bg-danger';
            statusElement.textContent = '异常';
        }
    } catch (error) {
        console.error('健康检查失败:', error);
        document.getElementById('systemStatus').className = 'badge bg-danger';
        document.getElementById('systemStatus').textContent = '连接失败';
    }
}

// 加载可用模型
async function loadAvailableModels() {
    try {
        const response = await fetch('/api/dsl/models');
        const data = await response.json();
        
        const modelsElement = document.getElementById('availableModels');
        modelsElement.className = 'badge bg-info';
        modelsElement.textContent = data.count + ' 个模型';
        
        // 更新模型选择下拉框
        const modelSelect = document.getElementById('model');
        modelSelect.innerHTML = '<option value="">使用默认模型</option>';
        
        data.models.forEach(model => {
            const option = document.createElement('option');
            option.value = model;
            option.textContent = model.toUpperCase();
            modelSelect.appendChild(option);
        });
        
    } catch (error) {
        console.error('加载模型失败:', error);
        document.getElementById('availableModels').textContent = '加载失败';
    }
}

// 加载支持的DSL类型
async function loadSupportedTypes() {
    try {
        const response = await fetch('/api/dsl/types');
        const data = await response.json();
        
        const typesElement = document.getElementById('supportedTypes');
        typesElement.className = 'badge bg-success';
        typesElement.textContent = data.count + ' 种类型';
        
    } catch (error) {
        console.error('加载DSL类型失败:', error);
        document.getElementById('supportedTypes').textContent = '加载失败';
    }
}

// 处理DSL生成
async function handleDslGeneration(event) {
    event.preventDefault();
    
    const spinner = document.getElementById('dslSpinner');
    const resultDiv = document.getElementById('dslResult');
    
    try {
        // 显示加载状态
        spinner.classList.remove('d-none');
        resultDiv.classList.add('d-none');
        
        // 收集表单数据
        const formData = collectDslFormData();
        
        // 发送请求
        const response = await fetch('/api/dsl/generate', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json'
            },
            body: JSON.stringify(formData)
        });
        
        const result = await response.json();
        
        // 显示结果
        displayDslResult(result);
        
    } catch (error) {
        console.error('DSL生成失败:', error);
        showError('DSL生成失败: ' + error.message);
    } finally {
        spinner.classList.add('d-none');
    }
}

// 收集DSL表单数据
function collectDslFormData() {
    const examples = document.getElementById('examples').value.trim();
    const context = document.getElementById('context').value.trim();
    
    const formData = {
        description: document.getElementById('description').value,
        dslType: document.getElementById('dslType').value,
        model: document.getElementById('model').value || undefined,
        examples: examples ? examples.split('\n').filter(line => line.trim()) : undefined,
        context: context ? JSON.parse(context) : undefined,
        params: {
            maxTokens: parseInt(document.getElementById('maxTokens').value),
            temperature: parseFloat(document.getElementById('temperature').value),
            validate: true
        }
    };
    
    return formData;
}

// 显示DSL生成结果
function displayDslResult(result) {
    const resultDiv = document.getElementById('dslResult');
    const contentElement = document.getElementById('dslContent');
    const statusElement = document.getElementById('dslStatus');
    const durationElement = document.getElementById('dslDuration');
    const requestIdElement = document.getElementById('dslRequestId');
    
    // 格式化并显示内容
    if (result.dslContent) {
        try {
            const formatted = JSON.stringify(JSON.parse(result.dslContent), null, 2);
            contentElement.textContent = formatted;
        } catch (e) {
            contentElement.textContent = result.dslContent;
        }
    } else {
        contentElement.textContent = result.errorMessage || '生成失败';
    }
    
    // 显示状态信息
    statusElement.textContent = result.status;
    statusElement.className = getStatusClass(result.status);
    
    durationElement.textContent = result.duration || 'N/A';
    requestIdElement.textContent = result.requestId || 'N/A';
    
    resultDiv.classList.remove('d-none');
}

// 处理业务规则生成
async function handleBusinessRuleGeneration(event) {
    event.preventDefault();
    
    const spinner = document.getElementById('ruleSpinner');
    const resultDiv = document.getElementById('businessRuleResult');
    
    try {
        spinner.classList.remove('d-none');
        resultDiv.classList.add('d-none');
        
        const formData = {
            ruleName: document.getElementById('ruleName').value,
            relatedField: document.getElementById('relatedField').value,
            ruleDescription: document.getElementById('ruleDescription').value
        };
        
        const response = await fetch('/api/business-rule/parse', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json'
            },
            body: JSON.stringify(formData)
        });
        
        const result = await response.json();
        displayBusinessRuleResult(result);
        
    } catch (error) {
        console.error('业务规则生成失败:', error);
        showError('业务规则生成失败: ' + error.message);
    } finally {
        spinner.classList.add('d-none');
    }
}

// 显示业务规则结果
function displayBusinessRuleResult(result) {
    const resultDiv = document.getElementById('businessRuleResult');
    const contentElement = document.getElementById('ruleContent');
    const statusElement = document.getElementById('ruleStatus');
    const durationElement = document.getElementById('ruleDuration');
    const requestIdElement = document.getElementById('ruleRequestId');
    
    if (result.dslContent) {
        try {
            const formatted = JSON.stringify(JSON.parse(result.dslContent), null, 2);
            contentElement.textContent = formatted;
        } catch (e) {
            contentElement.textContent = result.dslContent;
        }
    } else {
        contentElement.textContent = result.errorMessage || '生成失败';
    }
    
    statusElement.textContent = result.status;
    statusElement.className = getStatusClass(result.status);
    
    durationElement.textContent = result.duration || 'N/A';
    requestIdElement.textContent = result.requestId || 'N/A';
    
    resultDiv.classList.remove('d-none');
}

// 加载规则示例
function loadRuleExample(type) {
    let examples;

    if (typeof businessRuleExamples !== 'undefined') {
        examples = businessRuleExamples;
    } else {
        examples = {
            required: {
                ruleName: '作业申请单位校验_必填',
                relatedField: '作业申请单位',
                ruleDescription: '为空提示：{"des": "作业申请单位未填写。", "result": "错误"}'
            },
            format: {
                ruleName: '动火作业数据校验_格式',
                relatedField: '动火作业数据',
                ruleDescription: 'not in 节点值：微气象 输出：{"des": "动火作业数据填写格式错误。", "result": "错误"}'
            },
            range: {
                ruleName: '作业申请时间校验_范围',
                relatedField: '作业申请时间',
                ruleDescription: '如果作业申请时间不为空且作业申请时间早于申请时间，输出{"des": "作业申请时间不能早于申请时间。", "result": "错误"}'
            }
        };
    }

    const example = examples[type];
    if (example) {
        document.getElementById('ruleName').value = example.ruleName;
        document.getElementById('relatedField').value = example.relatedField;
        document.getElementById('ruleDescription').value = example.ruleDescription;
    }
}

// 加载DSL示例数据
function loadDslExample(type) {
    if (typeof dslExamples !== 'undefined' && dslExamples[type]) {
        const example = dslExamples[type];
        document.getElementById('description').value = example.description;
        document.getElementById('dslType').value = type;
        document.getElementById('examples').value = example.examples.join('\n');
        document.getElementById('context').value = JSON.stringify(example.context, null, 2);
    }
}

// 加载批量示例数据
function loadBatchExample() {
    let exampleData;

    if (typeof batchBusinessRuleExample !== 'undefined') {
        exampleData = batchBusinessRuleExample;
    } else {
        exampleData = {
            "rules": [
                {
                    "ruleName": "作业申请单位校验_必填",
                    "relatedField": "作业申请单位",
                    "ruleDescription": "为空提示：{\"des\": \"作业申请单位未填写。\", \"result\": \"错误\"}"
                },
                {
                    "ruleName": "作业申请时间校验_必填",
                    "relatedField": "作业申请时间",
                    "ruleDescription": "为空提示：{\"des\": \"作业申请时间未填写。\", \"result\": \"错误\"}"
                },
                {
                    "ruleName": "动火作业数据校验_格式",
                    "relatedField": "动火作业数据",
                    "ruleDescription": "not in 节点值：微气象 输出：{\"des\": \"动火作业数据填写格式错误。\", \"result\": \"错误\"}"
                }
            ]
        };
    }

    document.getElementById('batchRules').value = JSON.stringify(exampleData, null, 2);
}

// 处理批量规则解析
async function processBatchRules() {
    const spinner = document.getElementById('batchSpinner');
    const resultDiv = document.getElementById('batchResult');
    
    try {
        spinner.classList.remove('d-none');
        resultDiv.classList.add('d-none');
        
        const batchData = JSON.parse(document.getElementById('batchRules').value);
        
        const response = await fetch('/api/business-rule/parse-batch', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json'
            },
            body: JSON.stringify(batchData)
        });
        
        const result = await response.json();
        displayBatchResult(result);
        
    } catch (error) {
        console.error('批量处理失败:', error);
        showError('批量处理失败: ' + error.message);
    } finally {
        spinner.classList.add('d-none');
    }
}

// 显示批量处理结果
function displayBatchResult(result) {
    const resultDiv = document.getElementById('batchResult');
    
    // 更新统计信息
    document.getElementById('batchTotal').textContent = result.total || 0;
    document.getElementById('batchSuccess').textContent = result.success || 0;
    document.getElementById('batchFailed').textContent = result.failed || 0;
    document.getElementById('batchSuccessRate').textContent = 
        result.total > 0 ? Math.round((result.success / result.total) * 100) + '%' : '0%';
    
    // 显示详细结果
    const resultsContainer = document.getElementById('batchResults');
    resultsContainer.innerHTML = '';
    
    if (result.results) {
        Object.entries(result.results).forEach(([ruleId, ruleResult]) => {
            const resultCard = createResultCard(ruleId, ruleResult);
            resultsContainer.appendChild(resultCard);
        });
    }
    
    resultDiv.classList.remove('d-none');
}

// 创建结果卡片
function createResultCard(ruleId, ruleResult) {
    const card = document.createElement('div');
    card.className = 'card mb-2';
    
    const statusClass = getStatusClass(ruleResult.status);
    
    card.innerHTML = `
        <div class="card-header d-flex justify-content-between align-items-center">
            <h6 class="mb-0">${ruleId}</h6>
            <span class="${statusClass}">${ruleResult.status}</span>
        </div>
        <div class="card-body">
            ${ruleResult.dslContent ? 
                `<pre class="json-viewer small">${formatJson(ruleResult.dslContent)}</pre>` :
                `<div class="text-danger">${ruleResult.errorMessage || '生成失败'}</div>`
            }
        </div>
    `;
    
    return card;
}

// 获取状态样式类
function getStatusClass(status) {
    switch (status) {
        case 'SUCCESS':
            return 'status-success';
        case 'FAILED':
            return 'status-failed';
        case 'PARTIAL':
            return 'status-partial';
        default:
            return 'text-muted';
    }
}

// 格式化JSON
function formatJson(jsonString) {
    try {
        return JSON.stringify(JSON.parse(jsonString), null, 2);
    } catch (e) {
        return jsonString;
    }
}

// 复制到剪贴板
async function copyToClipboard(elementId) {
    const element = document.getElementById(elementId);
    const text = element.textContent;
    
    try {
        await navigator.clipboard.writeText(text);
        showSuccess('已复制到剪贴板');
    } catch (error) {
        console.error('复制失败:', error);
        showError('复制失败');
    }
}

// 显示成功消息
function showSuccess(message) {
    showToast(message, 'success');
}

// 显示错误消息
function showError(message) {
    showToast(message, 'danger');
}

// 显示提示消息
function showToast(message, type = 'info') {
    // 创建toast元素
    const toast = document.createElement('div');
    toast.className = `alert alert-${type} alert-dismissible fade show position-fixed`;
    toast.style.cssText = 'top: 20px; right: 20px; z-index: 9999; min-width: 300px;';
    toast.innerHTML = `
        ${message}
        <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
    `;
    
    document.body.appendChild(toast);
    
    // 3秒后自动移除
    setTimeout(() => {
        if (toast.parentNode) {
            toast.parentNode.removeChild(toast);
        }
    }, 3000);
}

// Excel文件处理相关函数

// 处理Excel文件选择
function handleExcelFileChange(event) {
    const file = event.target.files[0];
    const previewDiv = document.getElementById('excelPreview');

    if (file && document.getElementById('previewData').checked) {
        previewExcelData(file);
    } else {
        previewDiv.classList.add('d-none');
    }
}

// 预览Excel数据
async function previewExcelData(file) {
    try {
        // 这里可以使用SheetJS等库来预览Excel数据
        // 为了简化，我们只显示文件信息
        const previewDiv = document.getElementById('excelPreview');
        const countSpan = document.getElementById('previewCount');

        countSpan.textContent = '文件已选择: ' + file.name;
        previewDiv.classList.remove('d-none');

        showSuccess('文件已选择，点击"上传并解析"开始处理');

    } catch (error) {
        console.error('预览Excel数据失败:', error);
        showError('预览Excel数据失败: ' + error.message);
    }
}

// 处理Excel上传
async function handleExcelUpload(event) {
    event.preventDefault();

    const spinner = document.getElementById('uploadSpinner');
    const resultDiv = document.getElementById('excelResult');
    const fileInput = document.getElementById('excelFile');

    try {
        if (!fileInput.files[0]) {
            showError('请选择Excel文件');
            return;
        }

        spinner.classList.remove('d-none');
        resultDiv.classList.add('d-none');

        const formData = new FormData();
        formData.append('file', fileInput.files[0]);

        const response = await fetch('/api/business-rule/upload-excel', {
            method: 'POST',
            body: formData
        });

        const result = await response.json();

        if (response.ok) {
            displayExcelResult(result);
            showSuccess('Excel文件处理完成');
        } else {
            showError(result.error || 'Excel文件处理失败');
        }

    } catch (error) {
        console.error('Excel上传失败:', error);
        showError('Excel上传失败: ' + error.message);
    } finally {
        spinner.classList.add('d-none');
    }
}

// 显示Excel处理结果
function displayExcelResult(result) {
    const resultDiv = document.getElementById('excelResult');

    // 更新统计信息
    document.getElementById('excelFilename').textContent = result.filename || 'unknown';
    document.getElementById('excelOriginalCount').textContent = result.originalDataCount || 0;
    document.getElementById('excelTotal').textContent = result.total || 0;
    document.getElementById('excelSuccess').textContent = result.success || 0;
    document.getElementById('excelFailed').textContent = result.failed || 0;
    document.getElementById('excelSuccessRate').textContent =
        result.total > 0 ? Math.round((result.success / result.total) * 100) + '%' : '0%';

    // 显示详细结果
    const resultsContainer = document.getElementById('excelResults');
    resultsContainer.innerHTML = '';

    if (result.results) {
        Object.entries(result.results).forEach(([ruleId, ruleResult]) => {
            const resultCard = createResultCard(ruleId, ruleResult);
            resultsContainer.appendChild(resultCard);
        });
    }

    resultDiv.classList.remove('d-none');
}

// 处理Excel数据（从预览开始解析）
async function processExcelData() {
    const fileInput = document.getElementById('excelFile');
    if (fileInput.files[0]) {
        await handleExcelUpload({ preventDefault: () => {} });
    }
}

// 下载Excel模板
function downloadExcelTemplate() {
    // 创建Excel模板数据
    const templateData = [
        ['规则名称', '关联属性', '规则描述'],
        ['作业申请单位校验_必填', '作业申请单位', '为空提示：{"des": "作业申请单位未填写。", "result": "错误"}'],
        ['作业申请时间校验_必填', '作业申请时间', '为空提示：{"des": "作业申请时间未填写。", "result": "错误"}'],
        ['动火作业数据校验_格式', '动火作业数据', 'not in 节点值：微气象 输出：{"des": "动火作业数据填写格式错误。", "result": "错误"}']
    ];

    // 创建CSV内容
    const csvContent = templateData.map(row =>
        row.map(cell => `"${cell}"`).join(',')
    ).join('\n');

    // 创建下载链接
    const blob = new Blob(['\ufeff' + csvContent], { type: 'text/csv;charset=utf-8;' });
    const link = document.createElement('a');
    const url = URL.createObjectURL(blob);

    link.setAttribute('href', url);
    link.setAttribute('download', 'business_rules_template.csv');
    link.style.visibility = 'hidden';

    document.body.appendChild(link);
    link.click();
    document.body.removeChild(link);

    showSuccess('Excel模板已下载');
}
